# 好友管理
class Friend:
    def __init__(self):
        self.friend_li = []
    def welcome(self):
        print("* * 欢迎使用好友管理系统 * *")
        print("1:添加好友")
        print("2:删除好友")
        print("3:备注好友")
        print("4:展示好友")
        print("5:好友分组")
        print("6:退出")
        while True:
            option = input("请选择功能\n")
            # 添加好友
            if option == '1':
                self.add_friend()
            # 删除好友
            elif option == '2':
                self.del_friend()
            # 备注好友
            elif option == '3':
                self.modify_friend()
            # 展示好友
            elif option == '4':
                self.show_friend()
            # 分组好友
            elif option == '5':
                self.group_friend()
            elif option == '6':
                break
    # 添加好友
    def add_friend(self):
        add_friend = input("请输入要添加的好友:")
        self.friend_li.append(add_friend)
        print('好友添加成功')        
    # 获取好友
    def get_all_friends(self):
        new_li = []
        for friend_li_elem in self.friend_li:
            #判断元素类型
            if type(friend_li_elem) == dict:
                #遍历字典
                [new_li.append(dict_elem_name) for
                dict_elem in friend_li_elem.values()
                for dict_elem_name in dict_elem]
            else:
                new_li.append(friend_li_elem)
        return new_li 
    # 获取所有分组
    def get_all_groups(self):
        groups = []
        for friend_li_elem in self.friend_li:
            if type(friend_li_elem) == dict:
                groups.append(friend_li_elem)
        return groups
    # 获取所有分组名称
    def get_all_groups_name(self):
        groups_name = []
        for dict_elem in self.get_all_groups():
            for j in dict_elem:
                groups_name.append(j)
        return groups_name
    # 删除好友
    def del_friend(self):
        if len(self.friend_li) !=0:
            del_name = input("请输入删除好友姓名:")
            # 删除的好友未分组
            if del_name in self.friend_li:
                self.friend_li.remove(del_name)
                print('删除成功')
            else:
            #删除的好友在分组内
                if del_name in self.get_all_friends():
                    for group_data in self.get_all_groups():
                        for group_friend_li in group_data.values():
                            if del_name in group_friend_li: group_friend_li.remove(del_name)
                            continue
                        print('删除成功')
                    else:
                        print('好友的列表为空')
    # 备注好友
    def modify_friend(self):
        friends = self.get_all_friends()
        if len(friends)==0:
            print('好友列表为空')
        else:
            before_name = input("请输入要修改的姓名:")
            after_name = input("请输入要修改的姓名:")
            if before_name in self.friend_li:
                friends_index = self.friend_li.index(before_name)
                self.friend_li[friends_index] = after_name
                print("备注成功")
            elif before_name not in self.friend_li:
                for friend_li_elem in self.friend_li:
                    if type(friend_li_elem) == dict:
                        for dict_elem in friend_li_elem.values():
                            if before_name in dict_elem:
                                modify_index = dict_elem.index(before_name)
                                dict_elem[modify_index] = after_name
                                print('备注成功')
    # 展示好友
    def show_friend(self):
        print("1.展示所有好友姓名")
        print("2.展示分组名称")
        option_show = input("请输入选项:")
        groups = self.get_all_groups()
        friends = self.get_all_friends()
        if option_show == '1':
            # 展示所有好友
            if len(friends) == 0:
                print("当前没有任何好友")
            else:
                print(friends)
        elif option_show == '2':
            if len(friends) == 0:
                print("当前没有任何好友")
            else:
                if len(groups) == 0:
                    print("当前没有任何分组")
                else:
                #展示分组
                    for dict_groups in groups :
                        for groups_name in dict_groups:
                            print(groups_name)
                    is_show_group = input("是否展示组内好友: y/n\n")
                    if is_show_group == 'y':
                        show_group_name = input("请输入查看分组名称")
                        for i in groups:
                            if show_group_name in i:
                                show_index = groups.index(i)
                                print(groups[show_index][show_group_name])
    # 分组好友
    def group_friend(self):
        create_group = input("是否创建新的分组y/n\n")
        friends = self.get_all_friends()
        if create_group == 'y':
            if len(friends)==0:
                print("当前没有任何好友")
            else:
                # 请创建分组
                group_name = input("请输入分组名称：\n")
                group_name_li = list()
                # 展示当前好友
                print(friends)
                # 移动联系人到哪个组
                friend_name = input("请输入好友名称：\n")
                if friend_name in friends:
                    all_friend = []
                    for friend_li_elem in self.friend_li:
                        if type(friend_li_elem) == dict:
                            [all_friend.append(dict_friends) for
                             dict_elem in friend_li_elem.values()
                             for dict_friends in dict_elem]
                        else:
                            all_friend.append(friend_li_elem)
                    if friend_name in all_friend:
                        group_name_li.append(friend_name)
                        self.friend_li.remove(friend_name)
                        # 构建字典： {组名称：分组列表}
                        friend_dict = dict()
                        friend_dict[group_name] = group_name_li
                        self.friend_li.append(friend_dict)
                    else:
                        print("请输入正确的名称")
                else:
                    print('请输入正确好友名称')
        elif create_group =='n':
            # 显示当前的分组，将用户添加到指定的组
            current_groups = self.get_all_groups()
            print('当前分组:')
            for  current_group in current_groups:
                for group_name in current_group:
                    print(group_name)
            add_group = input('请选择添加的组:\n')
            # 判断用户输入的组名是否在当前已存在的分组名中
            if add_group in self.get_all_groups_name():
                # 添加好友到指定的组
                add_name = input('请选择添加的好友名称：\n')
                # 判断用户输入的好友是否存在好友列表中
                if add_name in self.friend_li:
                    # 判断用户是否在其他组中
                    if add_name not in current_groups:
                        # 将好友添加到指定的组内
                        add_group_index = \
                            self.get_all_groups_name().index(add_group)
                        current_groups[add_group_index][
                            add_group].append(add_name)
                else:
                    print('该好友已在其他分组中')
            else:
                print('请输入正确的组名')
    # 启动程序
    if __name__ == '__main__':
        friend = Friend()
        friend.welcome()

# 人机猜拳游戏
import random
class Player:
    def __init__(self):
        self.dict = {0: '剪刀', 1: '石头', 2: '布'}
    # 手势
    def gesture(self):
        player_input = int(input("请输入(0剪刀、1石头、2布:)"))
        return self.dict[player_input]
class AIPlayer(Player):
    play_data = []
    def ai_gesture(self):
        while True:
            computer = random.randint(0, 2)
            if len(self.play_data) >= 4:
                # 获取玩家出拳的最大概率
                max_prob = max(self.play_data, key=self.play_data.count)
                if max_prob == '剪刀':
                    return '石头'
                elif max_prob == '石头':
                    return '布'
                else:
                    return '剪刀'
            else:
                return self.dict[computer]
class Game:
    def game_judge(self):
        player = Player().gesture()
        AIPlayer().play_data.append(player)
        aiplayer = AIPlayer().ai_gesture()
        if (player == '剪刀' and aiplayer == '布') or \
                (player == '石头' and aiplayer == '剪刀') \
                or (player == '布' and aiplayer == '石头'):
            print(f"电脑出的手势是{aiplayer},恭喜，你赢了!")
        elif (player == '剪刀' and aiplayer == '剪刀') or \
                (player == '石头' and aiplayer == '石头') \
                or (player == '布' and aiplayer == '布'):
            print(f"电脑出的手势是{aiplayer},打成平局了！")
        else:
            print(f"电脑出的手势是{aiplayer},你输了，再接再厉！")
    def game_start(self):
        self.game_judge()
        while True:
            option = input("是否继续:y/n\n")
            if option=='y':
                self.game_judge()
            else:
                break
if __name__ == '__main__':
    g = Game()
    g.game_start()

# 自定义列表
class MyList:
    def __isnumber(self, n):
        if not isinstance(n, (int, float, complex)):
            return False
        return True
    # 构造函数，进行必要的初始化
    def __init__(self, *args):
        for arg in args:
            if not self.__isnumber(arg):
                print('所有的元素必须是数字类型')
                return
        self.__value = list(args)
    def __str__(self):
        return str(self.__value)
    def __del__(self):
        del self.__value
    # 重载运算符+
    def __add__(self, num):
        if self.__isnumber(num):
            # 数组中所有元素都与数字num相加
            my_list = MyList()
            my_list.__value = [elem + num for elem in self.__value]
            return my_list
    # 重载运算符-
    # 数组中每个元素都与数字num相减，返回新数组
    def __sub__(self, num):
        if not self.__isnumber(num):
            print('所有的元素必须是数字类型')
            return
        my_list = MyList()
        my_list.__value = [elem - num for elem in self.__value]
        return my_list
    # 重载运算符*
    # 数组中每个元素都与数字num相乘，返回新数组
    def __mul__(self, num):
        if not self.__isnumber(num):
            print('所有的元素必须是数字类型')
            return
        my_list = MyList()
        my_list.__value = [elem * num for elem in self.__value]
        return my_list
    # 重载运算符/
    # 数组中每个元素都与数字num相除，返回新数组
    def __truediv__(self, num):
        if not self.__isnumber(num):
            print('所有的元素必须是数字类型')
            return
        my_list = MyList()
        my_list.__value = [elem / num for elem in self.__value]
        return my_list

# 银行管理系统
class Card:
    def __init__(self,cardId,cardPwd,money):
        self.cardId = cardId
        self.cardPwd = cardPwd
        self.money = money
        self.cardLock = False
class User:
    def __init__(self, name, id, phone, card):
        self.name = name
        self.id = id
        self.phone = phone
        self.card = card
class Admin:
    adminU = '1'  # 管理员的账号
    adpwd = '1'  # 管理员的密码
    def printAdminView(self):
        print("******************************************")
        print("***                                    ***")
        print("***                                    ***")
        print("***         欢迎登录银行系统            ***")
        print("***                                    ***")
        print("***                                    ***")
        print("******************************************")
    def printsysFunctionView(self):
        print("***********************************************")
        print("***                                         ***")
        print("***    1.开户(1)                2.查询(2)   ***")
        print("***    3.取款(3)                4.存款(4)   ***")
        print("***    5.转账(5)                6.锁定(6)   ***")
        print("***    7.解锁(7)                            ***")
        print("***                                         ***")
        print("***    退出(Q)                              ***")
        print("***                                         ***")
        print("***********************************************")
    def adminOption(self):
        adminInput = input("请输入管理员账户：")
        if self.adminU != adminInput:
            print("管理员账户输入错误......")
            return -1
        passwordInput = input("请输入密码：")
        if self.adpwd != passwordInput:
            print("输入密码有误......")
            return -1
        else:
            print("操作成功，请稍后......")
            return 0
    from user import User
    from card import Card
    class ATM:
        def __init__(self, alluser):
            self.alluser = alluser
import random
def randomiCardId(self):     # 随机生成开户卡号
    while True:
        str_data = ''          # 存储卡号
        for i in range(6):    # 随机生成6位卡号
            ch = chr(random.randrange(ord('0'), ord('9') + 1))
            str_data += ch
        if not self.alluser.get(str):  # 判断卡号是否重复
            return str_data
def creatUser(self):
    # 目标向用户字典中添加一个键值对（卡号、用户对象）
    name = input("请输入姓名:")
    Uid = input("请输入身份证号:")
    phone = input("请输入手机号:")
    prestMoney = float(input("请输入预存金额:"))
    if prestMoney <= 0:
        print("预存款输入有误，开户失败")
        return -1
    oncePwd = input("请输入密码：")
    passWord = input("请再次输入密码：")
    if passWord != oncePwd:
        print("两次密码输入不同......")
        return -1
    print("密码设置成功，请牢记密码:  %s " % passWord)
    cardId = self.randomiCardId()
    card = Card(cardId, oncePwd, prestMoney)    # 创建卡
    user = User(name, Uid, phone, card)          # 创建用户
    self.alluser[cardId] = user                    # 存入用户字典
    print("您的开户已完成，请牢记开户账号: %s" % cardId)
def checkpwg(self, realPwd):
    for i in range(3):
        psd2 = input("请输入密码：")
        if realPwd == psd2:
            return True
    print("密码输错三次，系统自动退出......")
    return False
def lockCard(self):
    inptcardId = input("请输入您的卡号：")
    user = self.alluser.get(inptcardId)
    if not self.alluser.get(inptcardId):
        print("此卡号不存在...锁定失败！")
        return -1
    if user.card.cardLock:
        print("该卡已经被锁定，无需再次锁定！")
        return -1
    if not self.checkpwg(user.card.cardPwd):  # 验证密码
        print("密码错误...锁定失败！！")
        return -1
    user.card.cardLock = True
    print("该卡被锁定成功！")
def searchUser(self, base=1):
    if base == 2:
        inptcardId = input("请输入转出主卡号：")
    elif base == 3:
        inptcardId = input("请输入转入卡号：")
    elif base == 1:
        inptcardId = input("请输入您的卡号：")
    user = self.alluser.get(inptcardId)
    # 如果卡号不存在，下面代码就会执行
    if not self.alluser.get(inptcardId):
        print("此卡号不存在...查询失败！")
        return -1
    if user.card.cardLock:
        print("该用户已经被锁定...请解卡后使用！")
        return -1
    if not self.checkpwg(user.card.cardPwd):  # 验证密码
        print("密码错误过多...卡已经被锁定，请解卡后使用！")
        user.card.cardLock = True
        return -1
    if not base == 3:  # 查询转入账户   不打印余额
        print("账户: %s   余额: %.2f  " % (user.card.cardId, user.card.money))
    return user
def getMoney(self):
    userTF = self.searchUser()
    if userTF != -1:
        if userTF.card.cardId != '':
            inptMoney = float(input("请输入取款金额:"))
            if inptMoney > int(userTF.card.money):
                print("输入的金额大于余额，请先查询余额！")
                return -1
            userTF.card.money = float(userTF.card.money) – inptMoney
            print("取款成功！  账户: %s   余额: %.2f  " %
                (userTF.card.cardId, userTF.card.money))
    else:
        return -1
def saveMoney(self):
    userTF = self.searchUser()
    if userTF != -1:
        if not userTF.card.cardLock == True:
            if userTF.card.cardId != '':
                inptMoney = float(input("请输入要存入得金额:"))
                if inptMoney < 0:
                    print("请输入正确金额")
                else:
                    userTF.card.money += inptMoney
                    print("存款成功！  账户: %s   余额: %.2f  " %
                          (userTF.card.cardId, userTF.card.money))
    else:
        return -1
def transferMoney(self):
    MasterTF = self.searchUser(base=2)
    if (MasterTF == -1):
        return -1
    userTF = self.searchUser(base=3)
    if (userTF == -1):
        return -1
    in_tr_Money = float(input("请输入转账金额："))
    if MasterTF.card.money >= in_tr_Money:
        str = input("您确认要继续转账操作吗（y/n）？：")
        if str.upper() == "Y":
            MasterTF.card.money -= in_tr_Money
            userTF.card.money += in_tr_Money
            print("转账成功！  账户: %s   余额: %.2f  " %
                  (MasterTF.card.cardId, MasterTF.card.money))
        else:
            print("转账失败，中止了操作")
    else:
        print("转账失败,余额不足！  账户: %s   余额: %.2f  " %
              (MasterTF.card.cardId, MasterTF.card.money))
def unlockCard(self):
    inptcardId = input("请输入您的卡号：")
    user = self.alluser.get(inptcardId)
    while 1:
        if not self.alluser.get(inptcardId):
            print("此卡号不存在...解锁失败！")
            return -1
        elif not user.card.cardLock:
            print("该卡未被锁定，无需解锁！")
            break
        elif not self.checkpwg(user.card.cardPwd):
            print("密码错误...解锁失败！！")
            return -1
            user.card.cardLock = False  # 解锁
        print("该卡 解锁 成功！")
        break
from admin import Admin
from atm import ATM
import time
class HomePage:
    def __init__(self):
        self.allUserD = {}    # 使用字典存储数据
        self.atm = ATM(self.allUserD)
        self.admin = Admin()  # 管理员开机界面
    def saveUser(self):
        self.allUserD.update(self.atm.alluser)
        print("数据存盘成功")
# 程序的入口
    def main(self):
        self.admin.printAdminView()
        resL = self.admin.adminOption()
        if not resL:
            while True:
                self.admin.printsysFunctionView()
                option = input("请输入您的操作：")
                if option not in ("1", "2", "3", "4", "5",
                                  "6", "7", "S", "Q", "q"):
                    print("输入操作项有误,请仔细确认！")
                    time.sleep(1)
                if option == "1":  # 开户
                    self.atm.creatUser()
                elif option == "2":  # 查询
                    self.atm.searchUser()
                elif option == "3":  # 取款
                    self.atm.getMoney()
                elif option == "4":  # 存储
                    self.atm.saveMoney()
                elif option == "5":  # 转账
                    self.atm.transferMoney()
                elif option == "6":  # 锁定
                    self.atm.lockCard()
                elif option == "7":  # 解锁
                    self.atm.unlockCard()
                elif option.upper() == "Q":
                    if not (self.admin.adminOption()):
                        self.saveUser()
                        print('退出系统')
                        return -1
if __name__ == "__main__":
    homepage = HomePage()
    homepage.main()